package com.zking.note.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zking.note.pojo.User;
import com.zking.note.service.UserService;

@Controller
@RequestMapping("/account")
public class UserController {
	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	@ResponseBody
	public JsonResult<User> login(String name, String password,
			HttpServletRequest req, HttpServletResponse resp,
			HttpSession session) {
		session.setAttribute("name", name);
		System.out.println(name);
		try {
			User user = userService.login(name, password);

			return new JsonResult<User>(user);
		} catch (Exception e) {
			return new JsonResult<User>(e);
		}
	}

	@RequestMapping("/regist.do")
	@ResponseBody
	public JsonResult<User> regist(String name, String password, String nick) {
		try {
			User user = userService.regist(name, password, nick);
			return new JsonResult<User>(user);
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult<User>(e);
		}
	}

	@RequestMapping("/checkcode.do")
	@ResponseBody
	public void checkcode(HttpSession session, HttpRequest req,
			HttpServletResponse resp) throws IOException {
		System.out.println("in");
		String rand = (String) session.getAttribute("rand");
		String passcode = ((ServletRequest) req).getParameter("passcode");
		System.out.println("rand=" + rand);
		System.out.println("passcode=" + passcode);
		if (passcode.equalsIgnoreCase(rand)) {
			PrintWriter writer = resp.getWriter();
			writer.print("验证码正确");
		} else {
			PrintWriter writer = resp.getWriter();
			writer.print("验证码错误");
		}

	}
}
